//
//  DZYPageCollectionView.swift
//  DZYPageView
//
//  Created by dongzhenyu on 2017/8/2.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit


protocol DZYPageCollectionViewDataSource : class {
    
    // 有多少组数据
    func numberOfSectionInPageCollectionView(_ pageCollectionView: DZYPageCollectionView) -> Int
    // 每组里面有多少个数组
    func pageCollectionView(_ pageCollectionView: DZYPageCollectionView, numberOfItemsSection section: Int) -> Int
    // 每一个cell长什么样子
    func pageCollectionView(_ pageCollectionView: DZYPageCollectionView, _ collctionView: UICollectionView, cellAtIndexPath indexPath: IndexPath) -> UICollectionViewCell
    
}

class DZYPageCollectionView: UIView {

    weak var dataSource: DZYPageCollectionViewDataSource?
    
    fileprivate var titles: [String]
    fileprivate var style: DZYPageStyle
    fileprivate var layout: DZYPageCollectionLayout
    
    fileprivate var collectionView: UICollectionView!
    fileprivate var pageControl: UIPageControl!
    fileprivate lazy var currentIndex: IndexPath = IndexPath(item: 0, section: 0)
    fileprivate var titleView: DZYTitleView!
    
    
    init(frame: CGRect, titles: [String], style: DZYPageStyle, layout: DZYPageCollectionLayout) {
        self.titles = titles
        self.style = style
        self.layout = layout
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension DZYPageCollectionView {
    
    fileprivate func setupUI() {
        
        // 1. titleView
        let titleY = style.isTitleInTop ? 0 : bounds.height - style.titleHeight
        let titleFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: style.titleHeight)
        let titleView = DZYTitleView(frame: titleFrame, titles: titles, style: style)
        addSubview(titleView)
        titleView.backgroundColor = UIColor.randomColor()
        titleView.delegate = self
        self.titleView = titleView
        
        // 2.UICollectionView
        let collectionY = style.isTitleInTop ? style.titleHeight : 0
        let collectionH = bounds.height - style.titleHeight - style.pageControlHeight
        let collectionFrame = CGRect(x: 0, y: collectionY, width: bounds.width, height: collectionH)
        
        // 转移到控制器中
//        let layout = DZYPageCollectionLayout()
//        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
//        layout.lineMargin = 10
//        layout.itemMargin = 10
        
//        layout.itemSize = CGSize(width: 60, height: 60)
//        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: collectionFrame, collectionViewLayout: layout)
        addSubview(collectionView)
        collectionView.backgroundColor = UIColor.randomColor()
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.dataSource = self
        collectionView.delegate = self
//        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCollectionViewCellID)
        self.collectionView = collectionView // 赋值 避免强制解包崩溃
        
        
        // 3. UIPageControl
        let pageFrame = CGRect(x: 0, y: collectionFrame.maxY, width: bounds.width, height: style.pageControlHeight)
        let pageControl = UIPageControl(frame: pageFrame)
        pageControl.numberOfPages = 4
        addSubview(pageControl)
        pageControl.backgroundColor = UIColor.randomColor()
        self.pageControl = pageControl
    }
}


extension DZYPageCollectionView {
    
    func registerCell(_ cell: AnyClass?, reusableIdentifier: String) {
        collectionView.register(cell, forCellWithReuseIdentifier: reusableIdentifier)
    }
    
    func registerNib(_ nib: UINib?, reusableIdentifier: String) {
        collectionView.register(nib, forCellWithReuseIdentifier: reusableIdentifier)
    }
}

extension DZYPageCollectionView: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataSource?.numberOfSectionInPageCollectionView(self) ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let sectionItemCount = dataSource?.pageCollectionView(self, numberOfItemsSection: section) ?? 0
        
        if section == 0 {
            pageControl.numberOfPages = (sectionItemCount - 1) / (layout.cols * layout.rows) + 1
        }
        
        return sectionItemCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 
    
        // 可以强制解包 因为能来到这里 上面两个方法一定是有值的
        return (dataSource?.pageCollectionView(self, collectionView, cellAtIndexPath: indexPath))!
    }
}

extension DZYPageCollectionView: UICollectionViewDelegate {
    
    // 减速停止
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewEndScroll()
    }
    
    // 没有减速 只是拖拽的停止
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewEndScroll()
        }
    }
    
    private func scrollViewEndScroll() {
    
        // 1.获取滚动位置对应的indexPath
        // 系统的有bug
//        guard let cell = collectionView.visibleCells.first else {
//            return
//        }
//        
//        let indexPath = collectionView.indexPath(for: cell)!
//        indexPath.section
//        indexPath.item / (layout.rows * layout.cols)
        // 1.根据传入一个点 获取对应的indexPath
        let point = CGPoint(x: layout.sectionInset.left + 1 + collectionView.contentOffset.x, y: layout.sectionInset.top + 1)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {
            return
        }
        
        // 2.判断是否要改变组
        if indexPath.section != currentIndex.section {
            // 2.1 改变pageControl
            let itemsCount = dataSource?.pageCollectionView(self, numberOfItemsSection: indexPath.section) ?? 0
            pageControl.numberOfPages = (itemsCount - 1) / (layout.cols * layout.rows) + 1
        
            // 2.2改变titleView的变化
            titleView.setCurrentIndex(indexPath.section)
            
            // 2.3记录最新的indexPath
            currentIndex = indexPath
        }
        
        pageControl.currentPage = indexPath.item / (layout.cols * layout.rows)
    }
}


extension DZYPageCollectionView: DZYTitleViewDelegate {
    
    func titleView(_ titleView: DZYTitleView, targetIndex: Int) {
        // 1.根据targetIndex创建对应组的indexPath
        let indexPath = IndexPath(item: 0, section: targetIndex)
        
        // 2.滚动到正确的位置
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        
        // 3.设置pageControl的个数
        let sectionNum = dataSource?.numberOfSectionInPageCollectionView(self) ?? 0
        let sectionItemsNum = dataSource?.pageCollectionView(self, numberOfItemsSection: targetIndex) ?? 0
        pageControl.numberOfPages = (sectionItemsNum - 1) / (layout.cols * layout.rows) + 1
        pageControl.currentPage = 0
        // 4.设置最新的IndexPath
        currentIndex = indexPath
        
        // 5.调整正确的位置 <调整之前的位置偏移bug (最后一组会有位置问题)>
        if targetIndex == sectionNum - 1 && sectionItemsNum <= layout.cols * layout.rows {
            return
        }
        
        collectionView.contentOffset.x -= layout.sectionInset.left

    }
    
}

